<template>
	<div class="content-box add-good-argument">
		<el-form ref="formRef" class="good-store-form" :model="form" :rules="rules" label-width="100px">
			<div class="el-form-sub-title">基本信息</div>
			<el-form-item label="登录账号" prop="username">
				<el-input v-model="form.username" placeholder="输入登录账号" :maxlength="30" />
			</el-form-item>
			<el-form-item label="账号名称" prop="nickName">
				<el-input v-model="form.nickName" placeholder="输入账号名称" :maxlength="30" />
			</el-form-item>
			<el-form-item v-if="!editId" label="登录密码" prop="password">
				<el-input v-model="form.password" show-password placeholder="输入登录密码" minlength="6" :maxlength="16" />
			</el-form-item>
			<el-form-item v-if="!editId" label="确认密码" prop="confirmPassword">
				<el-input v-model="form.confirmPassword" show-password placeholder="输入登录密码" minlength="6" :maxlength="16" />
			</el-form-item>
			<el-form-item label="账号状态" prop="status">
				<el-radio-group v-model="form.status" class="w-full">
					<el-radio :value="0"> 启用 </el-radio>
					<el-radio :value="1"> 禁用 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="OA员工号" prop="oaId">
				<el-input v-model="form.oaId" placeholder="OA员工号" :maxlength="30" />
			</el-form-item>

			<div class="el-form-sub-title">操作权限</div>
			<el-form-item label="角色权限" prop="roleIdList">
				<el-checkbox-group v-model="form.roleIdList" @change="onRoleChange">
					<el-checkbox v-for="item in roleOptions" :key="item.id" :label="item.id" :value="item.id">{{ item.roleName }}</el-checkbox>
				</el-checkbox-group>
				<p class="el-upload__tip mt0 w-full">
					注意请勾选此账号属于的【角色权限】，对应的【权限明显】即可选中；<br />
					如果您还未设置过【角色权限】，请先设置角色权限；
				</p>
			</el-form-item>
			<el-form-item label-width="1" prop="type">
				<role-table :readOnly="true" :table-data="tableData" @checkbox-change="tableCheckChange"></role-table>
			</el-form-item>
			<el-divider direction="vertical" />
			<el-form-item label-width="0" style="position: absolute; right: 20px; bottom: 20px">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="tsx" name="addSystemAccount">
import { FormRules, ElMessage, dayjs } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import { Md5 } from 'ts-md5';
import { useRoute, useRouter } from 'vue-router';
import { fetchAccountDetail, fetchCreateAccount, fetchUpdateAccount, fetchRoleData, fetchRoleList, fetchPermissionByRoleIds } from '/@/api/system';
import { verifyAccount, verifyAccountName, verifyPassword } from '/@/utils/toolsValidate';
import roleTable from '../role/roleTable.vue';

const route = useRoute();
const router = useRouter();

const formRef = ref();
const form = ref<any>({
	status: 0,
});

const editId = ref();
const roleOptions = ref<any[]>([]);
let permissionData: any[] = [];
const tableData = ref<any[]>([]);

let timer: any = '';

// 用户勾选的菜单
let menuIdList: Array<number> = [];

// 表格里勾选事件回调
function tableCheckChange(backItem: any) {
	if (backItem.checked) {
		menuIdList.push(backItem.id);
	} else {
		menuIdList.forEach((item, index) => {
			if (item === backItem.id) {
				menuIdList.splice(index, 1);
			}
		});
	}
	const copy = JSON.parse(JSON.stringify([...new Set(menuIdList)]));
	// Object.assign(menuIdList, copy);
	menuIdList = copy;
}

const onRoleChange = (value: any) => {
	if (timer) {
		clearTimeout(timer);
	}
	if (value.length <= 0) {
		return;
	}
	timer = setTimeout(async () => {
		const data = JSON.parse(JSON.stringify(permissionData));
		const setChecked = (item: any, arr: any) => {
			arr.forEach((ele: any) => {
				ele.type == item.type && ele.id == item.id && (ele.checked = true);
				if (ele.children.length > 0) {
					setChecked(item, ele.children);
				}
			});
		};
		const res = await fetchPermissionByRoleIds({ roleIdList: value });
		if (res.code == 200) {
			res.data.forEach((value: any) => {
				setChecked(value, data);
			});
		}
		tableData.value = data;
	}, 500);
};

const validateAccount = (rule: any, value: any, callback: any) => {
	if (!verifyAccount(value)) {
		callback(new Error('登录账号仅支持数字、字母组合形式'));
	} else {
		callback();
	}
};

const validateName = (rule: any, value: any, callback: any) => {
	if (!verifyAccountName(value)) {
		callback(new Error('账号名称仅支持中英文'));
	} else {
		callback();
	}
};

const validatePassword = (rule: any, value: any, callback: any) => {
	if (!verifyPassword(value)) {
		callback(new Error('密码必须包含英文、数字、符号,长度在6-16之间'));
	} else {
		callback();
	}
};

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
	if (value !== form.value.password) {
		callback(new Error('两次输入的密码不一致'));
	} else {
		callback();
	}
};

//校验规则
const rules = reactive<FormRules<any>>({
	username: [
		{ required: true, message: '输入登录账号', trigger: 'blur' },
		{
			validator: validateAccount,
			trigger: 'blur',
		},
	],
	nickName: [
		{ required: true, message: '输入账号姓名', trigger: 'blur' },
		{
			validator: validateName,
			trigger: 'blur',
		},
	],
	password: [
		{ required: true, message: '输入登录密码', trigger: 'blur' },
		{
			validator: validatePassword,
			trigger: 'blur',
		},
	],
	confirmPassword: [
		{ required: true, message: '输入登录密码', trigger: 'blur' },
		{
			validator: validateConfirmPassword,
			trigger: 'blur',
		},
	],
	status: [{ required: true, trigger: 'blur', message: '账号状态不能为空' }],
	roleIdList: [{ required: true, trigger: 'blur', message: '角色权限不能为空' }],
});

const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = { ...form.value };
			console.log('editId', editId.value);
			if (!editId.value) {
				const password = Md5.hashStr(form.value.password);
				params.password = password;
			}
			const res = await (editId.value ? fetchUpdateAccount : fetchCreateAccount)(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑账号成功' : '新增账号成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const back = () => {
	router.push('/system/account');
};

const initData = async () => {
	// 获取角色列表
	const res: any = await fetchRoleList({ page: 1, size: 99999 });
	if (res.code == 200) {
		roleOptions.value = res.data.records;
	}
	// 获取权限数据
	const pRes: any = await fetchRoleData();
	if (res.code == 200) {
		permissionData = pRes.data;
		tableData.value = pRes.data;
	}
	editId.value = route.params.id;

	if (editId.value) {
		const res = await fetchAccountDetail({ id: editId.value });
		if (res.code === 200) {
			const data = res.data;
			data.roleIdList = data.checkRoleIdList;
			onRoleChange(data.roleIdList);
			form.value = data;
		}
	}
};

onMounted(() => {
	initData();
});
</script>

<style lang="scss">
.good-store-form {
	margin-bottom: 50px;
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number,
		.el-cascader,
		.el-date-editor {
			width: 100%;
			max-width: 450px;
		}
	}
	.el-table {
		.el-form-item {
			width: 80%;
			max-width: 150px;
			margin: auto;
		}
	}
}
</style>
